//
//  WQVideoPlayViewController.m
//  VideoDemo
//
//  Created by C on 2019/8/19.
//  Copyright © 2019 c. All rights reserved.
//

#import "WQVideoPlayViewController.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define SafeViewBottomHeight (kScreenHeight == 812.0 ? 34.0 : 0.0)

@interface WQVideoPlayViewController ()

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;

/// 视频组合器对象
@property (nonatomic, strong) AVMutableComposition *mutableComposition;
/// 可以用来对视频进行操作
@property (nonatomic, strong) AVMutableVideoComposition *mutableVideoComposition;

@property (nonatomic, strong) UIButton *completeButton;
@property (nonatomic, strong) WQExportVideoCommand *exportCommand;
@property (nonatomic, strong) UIProgressView *exportProgressView;
@property (nonatomic, strong) CALayer *watermarkLayer;

@end

@implementation WQVideoPlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self playWithUrl:self.fileUrl];
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(40, kScreenHeight-60-76-SafeViewBottomHeight, 76, 76)];
    [backButton setImage:[UIImage imageNamed:@"icon_return_n"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"icon_return_p"] forState:UIControlStateSelected];
    [backButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    
    self.completeButton = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-40-76, kScreenHeight-60-76-SafeViewBottomHeight, 76, 76)];
    [self.completeButton setImage:[UIImage imageNamed:@"icon_finish_p"] forState:UIControlStateNormal];
    [self.completeButton addTarget:self action:@selector(complete:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.completeButton];
    
    self.exportProgressView = [[UIProgressView alloc] init];
    self.exportProgressView.progressTintColor = [UIColor greenColor];
    self.exportProgressView.frame = CGRectMake(0, 0, 50, 4);
    self.exportProgressView.center = CGPointMake(self.completeButton.center.x, self.completeButton.center.y - 38 - 10);
    self.exportProgressView.layer.cornerRadius = 4;
    self.exportProgressView.layer.masksToBounds = YES;
    [self.view addSubview:self.exportProgressView];
    [self.exportProgressView setHidden:YES];
    
    //给AVPlayerItem添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(editCommandCompletionNotificationReceiver:)
                                                 name:AVSEEditCommandCompletionNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(exportCommandCompletionNotificationReceiver:)
                                                 name:AVSEExportCommandCompletionNotification
                                               object:nil];
    
    if (self.isOnlyPlay)
    {
        [self.completeButton setHidden:YES];
    } else
    {
        [self.completeButton setHidden:NO];
        [self addWatermark];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVSEEditCommandCompletionNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVSEExportCommandCompletionNotification object:nil];
}

-(void)back:(UIButton *)sender
{
    if (self.isOnlyPlay == NO) {
        [WQVideoFilePath removeVideoPathURL:self.fileUrl];
    }
    
    [self dismissViewControllerAnimated:NO completion:nil];
}

//导出视频
- (void)complete:(UIButton *)sender
{
    [self exportWillBegin];
    
    AVAsset *asset = [[AVURLAsset alloc] initWithURL:self.fileUrl options:nil];
    
    WQVideoEditCommand *exportCommand = [[WQExportVideoCommand alloc] initWithComposition:self.mutableComposition videoComposition:self.mutableVideoComposition];
    [exportCommand performWithAsset:asset];
    self.exportCommand = (WQExportVideoCommand *)exportCommand;
}

//添加水印
- (void)addWatermark
{
    AVAsset *asset = [[AVURLAsset alloc] initWithURL:self.fileUrl options:nil];
    
    WQVideoEditCommand *watermarkCommand = [[WQAddWatermarkCommand alloc] initWithComposition:self.mutableComposition videoComposition:self.mutableVideoComposition];
    [watermarkCommand performWithAsset:asset];
}

/** 播放方法 */
- (void)playWithUrl:(NSURL *)url
{
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    
    // 传入地址
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    // 播放器
    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    // 播放器layer
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = CGRectMake(0, 0, screenWidth, screenHeight);
    // 视频填充模式
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    // 添加到imageview的layer上
    [self.view.layer addSublayer:self.playerLayer];
    // 播放
    [self.player play];
}

- (void)reloadPlayerView
{
    // This method is called every time a tool has been applied to a composition
    // It reloads the player view with the updated composition
    // Create a new AVPlayerItem and make it our player's current item.
    if(self.watermarkLayer) {
        self.watermarkLayer.position = CGPointMake(130, 100);
        [self.view.layer addSublayer:self.watermarkLayer];
    }
}

//MARK: - 通知
/** 播放完成通知 */
- (void)playbackFinished:(NSNotification *)notification {
    NSLog(@"视频播放完成.");
    // 播放完成后重复播放
    // 跳到最新的时间点开始播放
    [self.player seekToTime: kCMTimeZero];
    [self.player play];
}

- (void)editCommandCompletionNotificationReceiver:(NSNotification*) notification
{
    if ([[notification name] isEqualToString:AVSEEditCommandCompletionNotification]) {
        // Update the document's composition, video composition etc
        self.mutableComposition = [[notification object] mutableComposition];
        self.mutableVideoComposition = [[notification object] mutableVideoComposition];
        //self.audioMix = [[notification object] mutableAudioMix];
//        if([[notification object] watermarkLayer])
//            self.watermarkLayer = [[notification object] watermarkLayer];
        
        self.watermarkLayer = [self watermarkLayerForSize];
        dispatch_async( dispatch_get_main_queue(), ^{
            [self reloadPlayerView];
        });
    }
}

- (void)exportCommandCompletionNotificationReceiver:(NSNotification *)notification
{
    if ([[notification name] isEqualToString:AVSEExportCommandCompletionNotification]) {
        dispatch_async( dispatch_get_main_queue(), ^{
            if (self.exportCommand.exportSession.error) {
                [self exportDidEnd: NO];
            } else
            {
                [self exportDidEnd: YES];
            }
        });
    }
}

- (void)updateExportProgress:(NSTimer*)timer
{
    self.exportProgressView.progress = self.exportCommand.exportSession.progress;
}

- (void)exportWillBegin
{
    // Hide play until the export is complete
    [self.completeButton setUserInteractionEnabled:NO];
    [[self exportProgressView] setHidden:NO];
    self.exportProgressView.progress = 0.0;
    [NSTimer scheduledTimerWithTimeInterval:0.05
                                     target:self
                                   selector:@selector(updateExportProgress:)
                                   userInfo:nil
                                    repeats:YES];
    
    if (self.watermarkLayer) {
        self.watermarkLayer.position = CGPointMake(130, 100);

        CALayer *exportWatermarkLayer = [CALayer layer];
        exportWatermarkLayer.frame = CGRectMake(0, 0, 960, 960);
        exportWatermarkLayer.anchorPoint = CGPointMake(0.5, 0.5);
        [exportWatermarkLayer addSublayer:self.watermarkLayer];

        CALayer *parentLayer = [CALayer layer];
        CALayer *videoLayer = [CALayer layer];
        CGFloat renderWidth = self.mutableVideoComposition.renderSize.width;
        CGFloat renderHeight = self.mutableVideoComposition.renderSize.height;
        parentLayer.frame = CGRectMake(0, 0, renderWidth, renderHeight);
        videoLayer.frame = CGRectMake(0, 0, renderWidth, renderHeight);
        [parentLayer addSublayer:videoLayer];
        [parentLayer addSublayer:exportWatermarkLayer];
        parentLayer.geometryFlipped = true;

        self.mutableVideoComposition.animationTool = [AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];
    }
}

- (void)exportDidEnd:(BOOL)isSucess
{
    // Update UI after export is completed
    NSLog(@"✅完成导出了");
    // 隐藏提示框 开始播放
    [self.player pause];
    [MBProgressHUD hideHUD];
    if (isSucess) {
        [MBProgressHUD showSuccess:@"合成完成"];
        [WQVideoFilePath removeVideoPathURL:self.fileUrl];
        [self dismissViewControllerAnimated:NO completion:nil];
        self.exportComplete(self.exportCommand.exporPath, self.exportCommand.exporName);
    } else {
        [MBProgressHUD showSuccess:@"合成失败"];
    }
    [self.completeButton setUserInteractionEnabled:YES];
}

//MARK: - 生成水印layer
//返回水印
- (CALayer *)watermarkLayerForSize
{
    CALayer *watermarkLayer = [CALayer layer];
    watermarkLayer.bounds = CGRectMake(0, 0, 200, 36);
    
    CALayer *logoLayer = [CALayer layer];
    logoLayer.frame = CGRectMake(0, 0, 36, 36);
    UIImage * image = [UIImage imageNamed:@"camera_logo_icon"];
    [logoLayer setContents:(__bridge id)image.CGImage];
    [watermarkLayer addSublayer:logoLayer];
    
    //名字
    CATextLayer *nameLayer = [self textLayerWithTitle:@"qqq" wtihFrame:CGRectMake(36, 0, 200-36 , 36)];
    [watermarkLayer addSublayer:nameLayer];
    
    //时间
    CATextLayer *timeLayer = [self textLayerWithTitle:@"2018-09-11 15:12:00" wtihFrame:CGRectMake(36, 15, 200-36 , 36)];
    [watermarkLayer addSublayer:timeLayer];
    
    return watermarkLayer;
}

- (CATextLayer *)textLayerWithTitle:(NSString *)title wtihFrame:(CGRect)frame
{
    CATextLayer *nameLayer = [CATextLayer layer];
    nameLayer.string = title;
    nameLayer.foregroundColor = [[UIColor whiteColor] CGColor];
    nameLayer.shadowOpacity = 0.5;
    nameLayer.alignmentMode = kCAAlignmentLeft;
    nameLayer.frame = frame;
    
    //choose a font
    UIFont *titleLayerFont = [UIFont systemFontOfSize:13];
    
    //set layer font
    CFStringRef fontName = (__bridge CFStringRef)titleLayerFont.fontName;
    CGFontRef fontRef = CGFontCreateWithFontName(fontName);
    nameLayer.font = fontRef;
    nameLayer.fontSize = titleLayerFont.pointSize;
    CGFontRelease(fontRef);
    return nameLayer;
}

@end
